/*
 * @Author: szx
 * @Date: 2022-07-01 15:43:09
 * @LastEditTime: 2022-07-05 17:23:40
 * @Description:.
 * @FilePath: \link_jump\src\components\TaskItem.tsx
 */
import React, { useState, useEffect, useCallback } from 'react';
import { Image, StyleSheet, TouchableOpacity, View, Text, Linking, Alert, TextInput } from 'react-native';
import Icon from 'react-native-vector-icons/Feather';
import BouncyCheckbox from 'react-native-bouncy-checkbox';

import editIcon from '../assets/icons/edit.png';
import { Task } from './TasksList';

interface TaskItemProps {
  index: number;
  task: Task;
  checkTask: (index: number) => void;
  updateTaskLink: (id: string, newLink: string) => void;
}

export const TaskItem: React.FC<TaskItemProps> = ({ index, task, checkTask, updateTaskLink }) => {
  const [checkboxState, setCheckboxState] = useState(task.checked);
  const [openStatus, setOpenStatus] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [taskLink, setTaskLink] = useState(task.link);

  useEffect(() => {
    setCheckboxState(task.checked);
  }, [task]);

  const handleCheckBox = () => {
    setCheckboxState(!task.checked);
    checkTask(index);
  };
  const openLink = useCallback(async () => {
    const supported = await Linking.canOpenURL(taskLink);
    if (supported) {
      await Linking.openURL(taskLink);
      setOpenStatus(true);
    } else {
      Alert.alert('链接必须以http(s)://开头', taskLink);
    }
  }, [taskLink]);

  function handleStartEdition() {
    setIsEditing(true);
  }

  function handleSubmitEditing() {
    if (taskLink && /https?:\/\//.test(taskLink)) {
      updateTaskLink(task.id, taskLink);
      setTaskLink(taskLink);
      setIsEditing(false);
    } else Alert.alert('格式错误', '链接必须以http(s)://开头');
  }

  return (
    <View>
      <View style={styles.itemContainer}>
        <BouncyCheckbox size={21} style={styles.checkbox} isChecked={checkboxState} disableBuiltInState disableText onPress={handleCheckBox} />
        {!isEditing ? (
          <Text style={openStatus ? styles.pressText : styles.taskText} onPress={openLink}>
            {task.name}
          </Text>
        ) : (
          <TextInput style={styles.editText} value={taskLink} onChangeText={setTaskLink} onSubmitEditing={handleSubmitEditing} />
        )}
        <View style={styles.iconsContainer}>
          <TouchableOpacity
            style={{
              paddingRight: 12
            }}
            onPress={!isEditing ? handleStartEdition : handleSubmitEditing}
          >
            {!isEditing ? <Image source={editIcon} /> : <Icon name="x" size={24} color="#bbb" />}
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  itemContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    marginHorizontal: 15,
    marginBottom: 10,
    justifyContent: 'space-between',
    backgroundColor: '#ffffff',
    borderWidth: 0.5,
    borderColor: '#b2b2b2',
    borderRadius: 20
  },
  checkbox: {
    marginLeft: 10
  },
  iconsContainer: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  editText: {
    height: 24,
    width: 270,
    textAlign: 'center',
    fontSize: 16,
    color: '#666',
    padding: 0,
    margin: 0
  },
  taskText: {
    width: 270,
    textAlign: 'center',
    height: 24,
    color: 'blue',
    fontSize: 16,
    textDecorationLine: 'underline'
  },
  pressText: {
    width: 270,
    height: 24,
    textAlign: 'center',
    fontSize: 16,
    color: '#666'
  }
});
